Page({
  data: {
    formData: {
      name: '',
      location: '',
      startWeek: '',
      endWeek: ''
    },
    classes: [],
    selectedClass: null,
    weekdays: ['周一', '周二', '周三', '周四', '周五'],
    selectedDay: null,
    timeSlots: [
      { label: '第一节 (8:00-9:40)', value: 0 },
      { label: '第二节 (10:00-11:40)', value: 1 },
      { label: '第三节 (14:00-15:40)', value: 2 },
      { label: '第四节 (16:00-17:40)', value: 3 },
      { label: '第五节 (19:00-20:40)', value: 4 }
    ],
    selectedTime: null
  },

  onLoad: function() {
    this.loadClasses();
  },

  loadClasses: function() {
    const that = this;
    wx.request({
      url: `${getApp().globalData.baseUrl}/api/classes/teacher`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success(res) {
        if (res.data.success) {
          that.setData({
            classes: res.data.classes
          });
        }
      }
    });
  },

  onClassChange: function(e) {
    const index = e.detail.value;
    this.setData({
      selectedClass: this.data.classes[index]
    });
  },

  onDayChange: function(e) {
    this.setData({
      selectedDay: parseInt(e.detail.value)
    });
  },

  onTimeChange: function(e) {
    this.setData({
      selectedTime: parseInt(e.detail.value)
    });
  },

  handleSubmit: function(e) {
    const formData = e.detail.value;
    
    // 表单验证
    if (!formData.name || !formData.location || 
        !this.data.selectedClass || this.data.selectedDay === null || 
        this.data.selectedTime === null || !formData.startWeek || !formData.endWeek) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    // 发送请求
    wx.request({
      url: `${getApp().globalData.baseUrl}/api/courses`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: {
        name: formData.name,
        location: formData.location,
        classId: this.data.selectedClass.id,
        dayIndex: this.data.selectedDay,
        timeIndex: this.data.selectedTime,
        startWeek: parseInt(formData.startWeek),
        endWeek: parseInt(formData.endWeek)
      },
      success(res) {
        if (res.data.success) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '添加失败',
            icon: 'none'
          });
        }
      }
    });
  }
});